package com.frank.start;

import org.apache.catalina.startup.Tomcat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@ComponentScan(basePackages = {"com.frank.start","com.frank.orderweb","com.frank.userweb"})
@SpringBootApplication
public class StartApplication {

    public static void main(String[] args) {
        SpringApplication.run(StartApplication.class, args);
    }
    @Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> webServerFactoryCustomizer() {
        return factory -> factory.addContextCustomizers(context -> {
            Tomcat.addServlet(context, "orderServlet", createDispatcherServlet("com.frank.orderweb.controller.OrderWebApplication"));
            context.addServletMappingDecoded("/order/*", "orderServlet");

            Tomcat.addServlet(context, "userServlet", createDispatcherServlet("com.frank.userweb.UserWebApplication"));
            context.addServletMappingDecoded("/user/*", "userServlet");
        });
    }
    private DispatcherServlet createDispatcherServlet(String configClass) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation(configClass);
        return new DispatcherServlet(context);
    }
}
